package com.beiing.tianshuai.tianshuai.mine.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.PersonalAuditAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.PersonalAuditBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryDetailActivity;
import com.beiing.tianshuai.tianshuai.huodong.ActivitiesDetailActivity;
import com.beiing.tianshuai.tianshuai.interest.InterestVideoDetailActivity;
import com.beiing.tianshuai.tianshuai.mine.presenter.PersonalAuditPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.PersonalAuditViewImpl;
import com.beiing.tianshuai.tianshuai.nim.session.SessionHelper;
import com.beiing.tianshuai.tianshuai.widget.CustomEmptyLayout;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;

/**
 * Create by Jinni 2018-1-3 11:49:39
 * <p>
 * 我的审核界面，展示用户发布的活动、新鲜事和兴趣的审核进度列表；
 */
public class PersonalAuditFragment extends BaseFragment implements PersonalAuditViewImpl {

    @BindView(R.id.refresh_header)
    MyRefreshHeader mRefreshHeader;
    @BindView(R.id.rv_audit_list)
    RecyclerView mRvAuditList;
    @BindView(R.id.refresh_footer)
    ClassicsFooter mRefreshFooter;
    @BindView(R.id.srl_my_refresh_layout)
    SmartRefreshLayout mSrlMyRefreshLayout;
    @BindView(R.id.empty_view)
    CustomEmptyLayout mEmptyView;

    public static final int PAGE_SIZE = 20;

    /**
     * 筛选条件
     * <p>
     * ["全部","发现审核","活动审核","兴趣审核"]
     */
    private String mSearch;

    /**
     * 当前分页类别
     * <p>
     * ["全部","审核中","已通过","未通过"]
     */
    private String mTypeName;

    /**
     * 适配器
     */
    private PersonalAuditAdapter mAdapter;

    /**
     * 判断是否加载完成
     */
    private boolean isLoadFinished = false;

    /**
     * 判断是否处于刷新状态
     */
    private boolean isRefresh = true;

    /**
     * 当前页码
     */
    private int pageNum = 1;

    /**
     * presenter
     */
    private PersonalAuditPresenter mPresenter;

    public static PersonalAuditFragment newInstance(String typeName, String search) {
        PersonalAuditFragment fragment = new PersonalAuditFragment();
        Bundle bundle = new Bundle();
        bundle.putString("typeName", typeName);
        bundle.putString("search", search);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_personal_audit;
    }

    @Override
    protected void init(View convertView) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mEmptyView.setInProgress();
            mTypeName = arguments.getString("typeName");
            mSearch = arguments.getString("search");
            initRefreshLayout();
            initRecyclerView();
            initPresenter();
            initListener();
        }
    }

    /**
     * 初始化RefreshLayout
     */
    private void initRefreshLayout() {
        mSrlMyRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSrlMyRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        // =================== 下拉刷新 =====================
        mSrlMyRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                isRefresh = true;
                isLoadFinished = false;
                mPresenter.requestData(UserInfoBean.getUid(mContext), mTypeName, mSearch, PAGE_SIZE, pageNum);
            }
        });
        // =================== 上拉加载 =====================
        mSrlMyRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinished) {
                    pageNum++;
                    isRefresh = false;
                    mPresenter.requestData(UserInfoBean.getUid(mContext), mTypeName, mSearch, PAGE_SIZE, pageNum);
                }
            }
        });
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvAuditList.setLayoutManager(manager);
        mAdapter = new PersonalAuditAdapter(mContext);
        mRvAuditList.setAdapter(mAdapter);
    }

    /**
     * 初始化presenter
     */
    private void initPresenter() {
        mPresenter = new PersonalAuditPresenter(this);
        mPresenter.requestData(UserInfoBean.getUid(mContext), mTypeName, mSearch, PAGE_SIZE, pageNum);
    }

    /**
     * 初始化点击事件
     */
    private void initListener() {
        mAdapter.setOnItemClickListener(new PersonalAuditAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(PersonalAuditBean.DataBean bean, int position) {
                Intent intent = new Intent();
                switch (bean.getTableType()) {
                    case "0":
                        intent.setClass(mContext, ActivitiesDetailActivity.class);
                        intent.putExtra("active_id", bean.getId());
                        startActivity(intent);
                        break;
                    case "2":
                        intent.setClass(mContext, DiscoveryDetailActivity.class);
                        intent.putExtra("fresh_id", bean.getId());
                        startActivity(intent);
                        break;
                    case "4":
                        intent.setClass(mContext, InterestVideoDetailActivity.class);
                        intent.putExtra("vid", bean.getId());
                        startActivity(intent);
                        break;
                }
            }
        });

        mAdapter.setOnContactClickListener(new PersonalAuditAdapter.OnContactClickListener() {
            @Override
            public void onContactClick(PersonalAuditBean.DataBean bean, int position) {
                PersonalAuditBean.DataBean.AuditorBean auditorBean = bean.getAuditor().get(0);
                SessionHelper.startP2PSession(mContext, auditorBean.getUid());
            }
        });
    }

    @Override
    public void showProgress() {
        mEmptyView.setInProgress();
    }

    @Override
    public void hideProgress() {
        if (mEmptyView != null) {
            mEmptyView.setChildrenVisible();
        }
    }

    @Override
    public void onRequestSuccess(PersonalAuditBean bean) {
        if (bean.getCode() == 200) {
            List<PersonalAuditBean.DataBean> dataBeans = bean.getData();
            if (!dataBeans.isEmpty()) {
                int size = dataBeans.size();
                if (!isRefresh) {
                    if (size == 0) {
                        isLoadFinished = true;
                        mSrlMyRefreshLayout.setLoadmoreFinished(true);
                    } else if (size == PAGE_SIZE) {
                        isLoadFinished = false;
                        mSrlMyRefreshLayout.setLoadmoreFinished(false);
                        mAdapter.appendData(dataBeans);
                    } else {
                        isLoadFinished = true;
                        mSrlMyRefreshLayout.setLoadmoreFinished(true);
                        mAdapter.appendData(dataBeans);
                    }
                    // 结束加载动画
                    if (mSrlMyRefreshLayout.isLoading()) {
                        mSrlMyRefreshLayout.finishLoadmore(true);
                    }
                } else {
                    // 判断刷新出的数据数量来更新视图
                    if (size == 0) {
                        isLoadFinished = true;
                        mSrlMyRefreshLayout.setLoadmoreFinished(true);
                        // 数据为空显示空数据提示的emptyView
                        mAdapter.clearData();
                        mEmptyView.setEmptyView(R.drawable.bg_empty_warning, "空空的");
                    } else if (size == PAGE_SIZE) {
                        isLoadFinished = false;
                        mSrlMyRefreshLayout.setLoadmoreFinished(false);
                        mAdapter.updateData(dataBeans);
                    } else {
                        isLoadFinished = true;
                        mSrlMyRefreshLayout.setLoadmoreFinished(true);
                        mAdapter.updateData(dataBeans);
                    }
                    mSrlMyRefreshLayout.finishRefresh(true);
                }
            } else {
                mAdapter.clearData();
                mSrlMyRefreshLayout.setLoadmoreFinished(true);
                mEmptyView.setEmptyView(R.drawable.bg_empty_warning, "空空的");
            }
        } else {
            if (!isRefresh) {
                pageNum--;
            }
            mAdapter.clearData();
            mSrlMyRefreshLayout.setLoadmoreFinished(false);
            mEmptyView.setEmptyView(R.drawable.bg_empty_warning, "请求失败");
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        // 如果当前不是刷新状态 那么只能是加载状态 如果失败要把之前加上去的页码减掉
        if (!isRefresh) {
            pageNum--;
        }
        // 如果刷新时请求数据失败 停止刷新动画
        if (mSrlMyRefreshLayout.isRefreshing()) {
            mSrlMyRefreshLayout.finishRefresh(false);
        }
        // 如果加载时请求数据失败 停止加载动画
        if (mSrlMyRefreshLayout.isLoading()) {
            mSrlMyRefreshLayout.finishLoadmore(false);
        }
    }

    public void chanFilter(String search) {
        isRefresh = true;
        isLoadFinished = false;
        mSearch = search;
        pageNum = 1;
        mPresenter.requestData(UserInfoBean.getUid(mContext), mTypeName, mSearch, PAGE_SIZE, pageNum);
    }
}
